package com.ifp.opengate.boot.task;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.ifp.opengate.boot.bean.access.AppAndApiVersionBean;
import com.ifp.opengate.boot.constants.Constants;
import com.ifp.opengate.boot.utils.RedisUtils;

/**
 */
@Component("accessCacheDataSyncHandler")
public class AccessCacheDataSyncTask {

    @Autowired
    private RedisUtils redisUtils;
    /**
     * 访问参数初始化
     */
    private Map<String, Map<Object, Object>> accessParamMap = new HashMap<String, Map<Object, Object>>();

    /**
     * APP API 数据版本缓存
     */
    @Autowired
    private AppAndApiVersionBean versionBean;

    @Value("${opengate_group_api}")
    private String opengateGroupApi;

    public Map<String, Map<Object, Object>> getAccessParamMap() {
        return accessParamMap;
    }

    @Value("${opengate_group_app}")
    private String opengateGroupApp;

    @Value("${opengate_group_secret}")
    private String opengateGroupSecret;

    @PostConstruct
    public void init() {
        // 加载redis记录得最新版本
        String apiInfoVersion =
            (String)redisUtils.get(Constants.OPEN_GATE_CACHE_NAME + "_" + Constants.API_DATA_VERSION);
        String appInfoVersion =
            (String)redisUtils.get(Constants.OPEN_GATE_CACHE_NAME + "_" + Constants.APP_DATA_VERSION);
        if (apiInfoVersion != versionBean.getAPI_VERSION()) {
            versionBean.setAPI_VERSION(apiInfoVersion);
        }
        if (appInfoVersion != versionBean.getAPP_VERSION()) {
            versionBean.setAPP_VERSION(appInfoVersion);
        }

        // 加载API APP信息
        reload();
        // 定时加载缓存：10分钟一次
        ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(1);
        scheduled.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (this) {
                        // 加载redis记录得最新版本
                        String apiInfoVersion =
                            (String)redisUtils.get(Constants.OPEN_GATE_CACHE_NAME + "_" + Constants.API_DATA_VERSION);
                        String appInfoVersion =
                            (String)redisUtils.get(Constants.OPEN_GATE_CACHE_NAME + "_" + Constants.APP_DATA_VERSION);
                        boolean isReflushFlag = !versionBean.getAPI_VERSION().equals(apiInfoVersion)
                            || !versionBean.getAPP_VERSION().equals(appInfoVersion);
                        // Trace.logInfo(Trace.MODULE_COMMON, "定时加载缓存信息accessParamMap,是否执行：{}", isReflushFlag);
                        // 有数据版本不对就刷新数据
                        if (isReflushFlag) {
                            versionBean.setAPI_VERSION(apiInfoVersion);
                            versionBean.setAPP_VERSION(appInfoVersion);
                            reload();
                        }
                    }
                } catch (Exception e) {
                    // Trace.log(Trace.MODULE_TASK, Trace.LEVEL_ERROR, "reload{} exception", e);
                }
            }
        }, 600, 600, TimeUnit.SECONDS);
    }

    public void reload() {
        try {
            //// Trace.log(Trace.MODULE_ACCESS, Trace.LEVEL_DEBUG, "start to reload access control's data");
            // 访问参数初始化
            initParam();
        } catch (Exception e) {
            // Trace.log(Trace.MODULE_INTERCEPTOR, Trace.LEVEL_ERROR, "init error!", e);
        }
    }

    /**
     * 访问参数初始化
     */
    public void initParam() {
        try {
            // Trace.log(Trace.MODULE_ACCESS, Trace.LEVEL_DEBUG, "start to reload access control's data");
            initAppInfo();

            // 获取api信息缓存
            // 缓存格式：key: "api_info_" + appId
            initApiInfo(opengateGroupApi);
            // 初始化密钥信息
            initSecrectInfo();
            // TODO 旧商户缓存信息
        } catch (Exception e) {
            // Trace.log(Trace.MODULE_INTERCEPTOR, Trace.LEVEL_ERROR, "init ChannelBandwidthConfigBean error!", e);
        }

    }

    private void initApiInfo(String opengateGroupApi) {
        Map<Object, Object> apiMap = redisUtils.hmget(opengateGroupApi);
        if (!apiMap.isEmpty()) {
            for (Map.Entry<Object, Object> entry : apiMap.entrySet()) {
                Map<Object, Object> apiInfo = redisUtils.hmget((String)entry.getKey());
                accessParamMap.put((String)entry.getKey(), apiInfo);
            }
        }
    }

    private void initAppInfo() {
        // 获取app信息缓存
        // 缓存格式：key: "app_info_" + appId
        initApiInfo(opengateGroupApp);
        // 产品状态列表
        Map<Object, Object> productInfo =
            redisUtils.hmget(Constants.OPEN_GATE_CACHE_NAME + "_" + Constants.PRODUCT_INFO_ALL);
        accessParamMap.put(Constants.OPEN_GATE_CACHE_NAME + "_" + Constants.PRODUCT_INFO_ALL, productInfo);
    }

    /**
     * 初始化密钥信息
     */
    private void initSecrectInfo() {
        // 获取secret信息缓存
        Map<Object, Object> secretMap = redisUtils.hmget(opengateGroupSecret);
        if (!secretMap.isEmpty()) {
            for (Map.Entry<Object, Object> entry : secretMap.entrySet()) {
                Map<Object, Object> secrectInfo = redisUtils.hmget((String)entry.getKey());
                accessParamMap.put((String)entry.getKey(), secrectInfo);
            }
        }
    }
}
